<template>
    <span :class="['bc-text-roll', { 'bc-text-roll-enable': enable }]" :data-label="label" :style="{
        width: typeof width === 'number' ? `${width}px` : width,
        '--roll-time': rollTime,
        ...style,
    }" v-bind="attrs" />
</template>

<script setup>
import { computed, useAttrs } from 'vue';

const props = defineProps({
    label: [String, Number],
    width: {
        type: [String, Number],
        default: 120,
    },
    enable: {
        type: Boolean,
        default: true,
    },
    duration: {
        type: Number,
        default: 500,
    },
    style: Object,
});

const attrs = useAttrs();

// 计算滚动时间（网页6动画时长处理思想）
const rollTime = computed(() => {
    const length = String(props.label || '').length;
    const duration = props.duration >= 0 ? props.duration : 500;
    return `${length * duration}ms`;
});
</script>

<style lang="less" scoped>
.bc-text-roll {
    position: relative;
    display: inline-flex;
    overflow: hidden;

    &::before {
        content: attr(data-label);
        white-space: nowrap;
    }

    &-enable {

        &::before,
        &::after {
            content: attr(data-label);
            white-space: nowrap;
            padding-right: 2em;
            animation: text-roll var(--roll-time) linear infinite;
        }
    }
}

@keyframes text-roll {

    0%,
    10% {
        transform: translateX(0);
    }

    90%,
    100% {
        transform: translateX(-100%);
    }
}
</style>
